//
//  UITextField+Ext.swift
//  CocoProject
//
//  Created by Vill on 2023/11/3.
//

import Foundation
import UIKit

extension UITextField{
    
    // 添加左间距
    func addLeftTextFieldPadding(_ padding:CGFloat){
        let leftView = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: frame.height))
        self.leftView = leftView
        self.leftViewMode = .always
    }
    
    /// 添加左侧图标
    ///
    /// - Parameters:
    ///   - image: 图标
    ///   - padding: 距离大小
    func addPaddingLeftIcon(_ image: UIImage, padding: CGFloat) {
        let imageView = UIImageView(image: image)
        imageView.contentMode = .center
        leftView = imageView
        leftView?.frame.size = CGSize(width: image.size.width + padding, height: image.size.height)
        leftViewMode = .always
    }
    
    // 替换清楚按钮
    func modifyClearButton(_ image : UIImage) {
        let rightview = UIView(frame: CGRect(x: 0, y: 0, width: 45, height: 40))
        let clearButton = UIButton(type: .custom)
        clearButton.setImage(image, for: .normal)
        clearButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        clearButton.contentMode = .scaleAspectFit
        clearButton.addTarget(self, action: #selector(clear), for: .touchUpInside)
        rightview.addSubview(clearButton)
        self.rightView = rightview
        self.rightViewMode = .whileEditing
    }

    @objc func clear(){
        self.text = ""
    }
}

